package com.cos.hospital.ui.usercenter;

import android.content.Intent;
import android.view.View;
import android.widget.GridView;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.init.BaseActivity;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.bean.user.SchBean;
import com.cos.hospital.model.bean.user.SchMineBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.UDialog;
import com.cos.hospital.tool.ULog;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.usercenter.adapter.SchGridWeekAdapter;
import com.cos.hospital.widget.ProgressDialog;
import com.google.gson.JsonObject;

import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * @Description: 我的排班
 * @Author: Kosmos
 * @Date: 2018年09月15日 23:52
 * @Email: KosmoSakura@foxmail.com
 */
public class SchedulingActivity extends BaseActivity {
    @BindView(R.id.sch_gv)
    GridView gv;
    private SchGridWeekAdapter adapter;
    private int userid;
    private SchBean[] list = new SchBean[32];
    private int[] schs = new int[7];
    private String[] weeks = new String[]{"一", "二", "三", "四", "五", "六", "日"};
    private boolean isFuture;//是否是未来
    private int weekCount;//前后周次数
    private String weekShow;//当前展示日期
    private boolean locked = false;//锁定点击

    @Override
    protected int layout() {
        return R.layout.activity_scheduling;
    }

    @Override
    protected void init() {
        setTitleLeftIcon();
        setTitleCenterTxt(getString(R.string.my_scheduling));
        setTitleRightTxt(getString(R.string.save));
        userid = SPUtil.getUserId();
        adapter = new SchGridWeekAdapter(list, context);
        gv.setAdapter(adapter);
    }

    /**
     * 1.顶部区域左侧默认显示当前日期所在周的日期起始，
     * 右侧左箭头点击后以当前日期前翻一周，最多至本周前三周；
     * 右侧右箭头点击后以当前日期后翻一周，最多至本周后三周；
     * 每次点击左右箭头时左侧部分日期实时变动；每次点击左右箭头后，下方排班情况实时变动；
     * <p>
     * 2.紧挨顶部区域展示排班情况，今日及今日以前日期排班情况灰化不能点击，
     * 今日可选日期内可修改排班情况；
     * <p>
     * 3.点击默认排班，进入默认排班编辑；
     * <p>
     * 4.点击保存，保存本次修改排班情况；
     * <p>
     * 默认排班创建和修改已经合并了
     * 排班暂时修改成下面
     * 0是无排班， 1是早上排班， 2是下午排班， 3是晚上，
     * 4是早上＋下午， 5是早上＋晚上，6是下午＋晚上，7是全天（早中晚）
     */
    @Override
    protected void logic() {

        gv.setOnItemClickListener((parent, view, position, id) -> {
            if (locked) {
                return;
            }
            if (position >= 0 && position < list.length && list[position] != null) {
                if (list[position].getType() == SchGridWeekAdapter.T_SELECT) {
                    if (list[position].isFuture()) {
                        list[position].setSelect(!list[position].isSelect());
                        adapter.setSelectPosition(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        locked = true;
                        showNotice("过去的排班不能修改", (result, dia) -> {
                            locked = false;
                            dia.dismiss();
                        });
                    }
                }
            }
        });

        initFrame();
        weekCount = 0;
        weekShow = UDate.getDateNow();
        getAGroup(UDate.getDateNow());
    }

    private void getAGroup(String date) {
        ProgressDialog.getInstance().startProgressDialog(this, "加载中");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldStartTime", date);
        jsonObject.addProperty("fldDoctorId", userid);
        UHttp.start(getServes().getSchedule(jsonObject), "排班查询", new HttpMsgListener<ResultBean<SchMineBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                ProgressDialog.getInstance().stopProgressDialog();
                showNotice(describe);
            }

            @Override
            public void onSuccess(ResultBean<SchMineBean> dto) {
                if (dto.isSuccess()) {
                    SchMineBean result = dto.getResult();
                    if (result == null) {
                        showNotice("数据异常");
                        ProgressDialog.getInstance().stopProgressDialog();
                        return;
                    }
                    schs[0] = result.getFldMonday();
                    schs[1] = result.getFldTuesday();
                    schs[2] = result.getFldWednesday();
                    schs[3] = result.getFldThursday();
                    schs[4] = result.getFldFriday();
                    schs[5] = result.getFldSaturday();
                    schs[6] = result.getFldSunday();
                    initAWeek(toParseWeek(result.getFldStartTime(), result.getFldEndTime()));
                } else {
                    ProgressDialog.getInstance().stopProgressDialog();
                    weekCount++;//倒数第n周没有数据，回复1
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * @param start 星期一的日期
     * @param end   星期日的日期
     * @return 一周7天的日期： 11/12
     */
    private String[] toParseWeek(String start, String end) {
        String[] date = new String[7];
        Calendar calendarStart = UDate.strToCalendar(start);
        Calendar calendarEnd = UDate.strToCalendar(end);
        if (calendarStart != null && calendarEnd != null) {
            int monthStart = calendarStart.get(Calendar.MONTH) + 1;
            int dayStart = calendarStart.get(Calendar.DATE);
            int monthEnd = calendarEnd.get(Calendar.MONTH) + 1;
            if (monthStart == monthEnd) {
                for (int i = 0; i < 7; i++) {
                    date[i] = monthStart + "/" + (dayStart + i);
                }
            } else {
                int diff = calendarStart.getActualMaximum(Calendar.DAY_OF_MONTH) - dayStart + 1;
                int newMonth = 1;
                for (int i = 0; i < 7; i++) {
                    if (i < diff) {
                        date[i] = monthStart + "/" + (dayStart + i);
                    } else {
                        date[i] = monthEnd + "/" + newMonth;
                        newMonth++;
                    }
                }
            }
        }
        return date;
    }

    /**
     * 绘制边框
     */
    private void initFrame() {
        list[0] = new SchBean(SchGridWeekAdapter.T_CLASS, "排班");
        list[8] = new SchBean(SchGridWeekAdapter.T_CLASS, "上午");
        list[16] = new SchBean(SchGridWeekAdapter.T_CLASS, "下午");
        list[24] = new SchBean(SchGridWeekAdapter.T_CLASS, "晚上");
        for (int i = 0; i < weeks.length; i++) {
            list[i + 1] = new SchBean(SchGridWeekAdapter.T_WEEK, weeks[i]);
            initMark(schs[i], i + 1);//先添加空事件,防止崩溃
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * @param dates 一周7天的日期： 11/12
     */
    private void initAWeek(String[] dates) {
        int dayOfWeek;//今天是周几？
        //本周
        if (weekCount == 0) {
            dayOfWeek = UDate.getDayOfWeek(new Date()) - 1;
        } else if (weekCount > 0) {
            dayOfWeek = -1;
        } else {
            dayOfWeek = 8;
        }
        ULog.commonD("dayOfWeek:" + dayOfWeek);
        boolean wroung = UTxt.isEmpty(dates[0]);
        for (int point = 0; point < 7; point++) {
            list[point + 1] = new SchBean(SchGridWeekAdapter.T_WEEK, weeks[point], wroung ? "--/--" : dates[point]);
            isFuture = point > dayOfWeek;
            initMark(schs[point], point + 1);
        }
        ProgressDialog.getInstance().stopProgressDialog();
        adapter.notifyDataSetChanged();
    }

    /**
     * @param position 位置
     * @param select   是否排班
     */
    private void inputSelect(int position, boolean select) {
        list[position] = new SchBean(SchGridWeekAdapter.T_SELECT, select, isFuture);
    }

    /**
     * @param point 位置
     * @param mark  0是无排班， 1是早上排班， 2是下午排班， 3是晚上，
     *              4是早上＋下午， 5是早上＋晚上，6是下午＋晚上，7是全天（早中晚）
     */
    private void initMark(int mark, int point) {
        switch (mark) {
            case 0:
                inputSelect(point + 8, false);
                inputSelect(point + 16, false);
                inputSelect(point + 24, false);
                break;
            case 1:
                inputSelect(point + 8, true);
                inputSelect(point + 16, false);
                inputSelect(point + 24, false);
                break;
            case 2:
                inputSelect(point + 8, false);
                inputSelect(point + 16, true);
                inputSelect(point + 24, false);
                break;
            case 3:
                inputSelect(point + 8, false);
                inputSelect(point + 16, false);
                inputSelect(point + 24, true);
                break;
            case 4:
                inputSelect(point + 8, true);
                inputSelect(point + 16, true);
                inputSelect(point + 24, false);
                break;
            case 5:
                inputSelect(point + 8, true);
                inputSelect(point + 16, false);
                inputSelect(point + 24, true);
                break;
            case 6:
                inputSelect(point + 8, false);
                inputSelect(point + 16, true);
                inputSelect(point + 24, true);
                break;
            case 7:
                inputSelect(point + 8, true);
                inputSelect(point + 16, true);
                inputSelect(point + 24, true);
                break;
        }
    }

    @OnClick({R.id.title_back, R.id.title_next_txt, R.id.sch_default,
        R.id.sch_last_week, R.id.sch_this_week, R.id.sch_next_week})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.title_next_txt://Save:
                save();
                break;
            case R.id.sch_last_week://上一周:
                if (weekCount <= -3) {
                    showNotice("最多至本周前三周");
                    return;
                }
                weekCount--;
                weekShow = UDate.getAnotherWeekDate(false, 1, weekShow);
                getAGroup(weekShow);
                ULog.commonD("-->" + weekCount);
                break;
            case R.id.sch_this_week://本周:
                weekCount = 0;
                weekShow = UDate.getDateNow();
                getAGroup(weekShow);
                ULog.commonD("-->" + weekCount);
                break;
            case R.id.sch_next_week://下一周:
                if (weekCount >= 3) {
                    showNotice("最多至本周后三周");
                    return;
                }
                weekCount++;
                weekShow = UDate.getAnotherWeekDate(true, 1, weekShow);
                getAGroup(weekShow);
                ULog.commonD("-->" + weekCount);
                break;
            case R.id.sch_default://默认排班:
                startActivity(new Intent(context, SchedulingDefaultActivity.class));
                break;
        }
    }

    /**
     * 排班保存
     */
    private void save() {
        String[] fldSchs = new String[]{"fldMonday", "fldTuesday", "fldWednesday", "fldThursday", "fldFriday", "fldSaturday", "fldSunday"};
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("fldStartTime", UDate.getMonday(weekShow));
        jsonObject.addProperty("fldEndTime", UDate.getSunday(weekShow));
        for (int i = 0; i < fldSchs.length; i++) {
            jsonObject.addProperty(fldSchs[i], checkSchResult(list[i + 9].isSelect(), list[i + 17].isSelect(), list[i + 25].isSelect()));
        }
        ProgressDialog.getInstance().startProgressDialog(this, "保存中");
        UHttp.start(getServes().getScheduleSave(jsonObject), "排班保存", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                showNotice(describe);
            }

            @Override
            public void onFinish() {
                ProgressDialog.getInstance().stopProgressDialog();
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    UDialog.getInstance(context, false, false)
                        .showNoticeWithOnebtn("排班修改成功!");
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * @param morning 早上是否排班
     * @param noon    中午排班情况
     * @param night   晚上排班情况
     * @return 0是无排班， 1是早上排班， 2是下午排班， 3是晚上，
     * 4是早上＋下午， 5是早上＋晚上，6是下午＋晚上，7是全天（早中晚）
     */
    private int checkSchResult(boolean morning, boolean noon, boolean night) {
        if (morning && noon && night) {
            return 7;
        } else if (morning && noon) {
            return 4;
        } else if (morning && night) {
            return 5;
        } else if (noon && night) {
            return 6;
        } else if (morning) {
            return 1;
        } else if (noon) {
            return 2;
        } else if (night) {
            return 3;
        } else {
            return 0;
        }
    }
}
